#include"Game.h"

void InitBoard(char board[ROWS][COLS], int row, int col, char set)
{
	for (int i = 0; i < row; ++i)
	{
		for (int j = 0; j < col; ++j)
		{
			board[i][j] = set;
		}
	}
}

void DisplayBoard(char board[ROWS][COLS], int row, int col)
{
	for (int i = 0; i <= col; ++i)
		printf("%d ", i);
	printf("\n");
	for (int i = 1; i <= row; ++i)
	{
		printf("%d ", i);
		for (int j = 1; j <= col; ++j)
		{
			printf("%c ", board[i][j]);
		}
		printf("\n");
	}
}

void SetMine(char mine[ROWS][COLS], int row, int col)
{
	int count = EASY_COUNT;
	srand(time(0));
	while (count)
	{
		int x = rand() % row + 1;
		int y = rand() % col + 1;
		if (mine[x][y] == '0')
		{
			mine[x][y] = '1';
			count--;
		}
	}
}

int GetMineCount(char mine[ROWS][COLS], int x, int y)
{
	return mine[x - 1][y - 1] + mine[x - 1][y] + mine[x - 1][y + 1] +mine[x][y - 1] + mine[x][y + 1] +mine[x + 1][y - 1] + mine[x + 1][y] + mine[x + 1][y + 1] - (8 * '0');
}

void FindMine(char mine[ROWS][COLS], char show[ROWS][COLS],int row, int col)
{
	int win = 0;
	int x, y;
	while (win < row * col - EASY_COUNT)
	{
		printf("请输入坐标:>");
		scanf("%d %d", &x, &y);
		if ((x >= 1 && x <= row) && (y >= 1 && y <= col))
		{
			if (mine[x][y] == '1')
			{
				DisplayBoard(mine, ROW, COL);
				printf("游戏结束，你输了\n");
				break;
			}

			int n = GetMineCount(mine, x, y);
			show[x][y] = n + '0';
			system("cls");
			DisplayBoard(show, ROW, COL);
			win++;
		}
		else
		{
			printf("输入错误，请重新输入\n");
		}
	}

	if (win >= row * col - EASY_COUNT)
	{
		printf("游戏结束，你赢了\n");
		DisplayBoard(mine, ROW, COL);
	}
}

void StartGame()
{
	char mine[ROWS][COLS];
	char show[ROWS][COLS];

	//初始化棋盘
	InitBoard(mine, ROWS, COLS, '0');
	InitBoard(show, ROWS, COLS, '*');

	//埋雷
	SetMine(mine, ROW, COL);

	//展示雷区
	DisplayBoard(show, ROW, COL);

	//扫雷
	FindMine(mine, show, ROW, COL);

}